<route lang="jsonc" type="page">
    {
      "layout": "default",
      "style": {
			"navigationStyle": "custom",
			"navigationBarTitleText": "线下店铺"
		}
    }
</route>

<script lang="ts" setup>
import { ref } from 'vue'
import { getStoreList } from '@/api/home'
import { useSafeAreaInsets } from '@/mixins/basic'
import HeaderNavbar from '@/pages/components/header-navbar.vue'

defineOptions({
  name: 'Store',
})

const { safeAreaInsets } = useSafeAreaInsets()

const storeArr = ref<Record<string, any>>([])

onShow(async () => {
  const location = await getLocation()

  initStoreList(location)
})
// 获取门店列表
function initStoreList(location: AnyObject) {
  getStoreList().then((res) => {
    res.forEach((item: AnyObject) => {
      // 会匹配 0, null, undefined, '', NaN
      const hasInvalid = [location.lat, location.lng, item.latitude, item.longitude].some(val => !val)
      // 存在无效的经纬度值（包括 0）
      if (hasInvalid) {
        item.distance = '-未知'
        return
      }

      const distanceInMeters = calculateDistance(
        location.lat,
        location.lng,
        item.latitude,
        item.longitude,
      )
      const formattedDistance = formatDistance(distanceInMeters)
      item.distance = formattedDistance
    })
    storeArr.value = res
  })
}
// 获取用户当前定位
function getLocation() {
  let location = {
    lat: 0,
    lng: 0,
  }
  return new Promise((reserve, reject) => { // 因为获取位置是异步接口所以需要使用promise
    uni.getFuzzyLocation({
      type: 'wgs84', // 可选参数，默认为 wgs84，表示返回的坐标系。其他值如 gcj02 表示国测局坐标系。
      success(res) {
        location.lat = res.latitude
        location.lng = res.longitude,
        reserve(location)
      },
      fail(err) {
        reserve(location)// 获取失败则返回经纬坐标为0
      },
    })
  })
}

// 计算两点间距离（Haversine 公式，单位：米）
function calculateDistance(lat1: any, lng1: any, lat2: any, lng2: any) {
  const R = 6371000 // 地球半径，单位：米
  const toRad = (angle: number) => (angle * Math.PI) / 180

  const dLat = toRad(lat2 - lat1)
  const dLng = toRad(lng2 - lng1)
  const lat1Rad = toRad(lat1)
  const lat2Rad = toRad(lat2)

  const a
			= Math.sin(dLat / 2) * Math.sin(dLat / 2)
			  + Math.cos(lat1Rad)
			  * Math.cos(lat2Rad)
			  * Math.sin(dLng / 2)
			  * Math.sin(dLng / 2)

  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  return R * c // 返回距离，单位：米
}

// 格式化距离：小于 1km 显示 m，否则显示 km
function formatDistance(meters: any) {
  if (meters < 1000) {
    `${Math.round(meters)} m`
  }
  else {
    return `${(meters / 1000).toFixed(2)} km`
  }
}

// function handleBack() {
// 	uni.navigateBack({})
// }
</script>

<template>
	<!--  -->
	<view class="store-page" :style="{ marginTop: `${safeAreaInsets?.top}px`, height: `calc(100vh - ${safeAreaInsets?.top}px)` }">
		<!-- <wd-navbar title="线下店铺" fixed left-arrow safeAreaInsetTop :bordered='false' @click-left="handleBack"></wd-navbar> -->
		<header-navbar title="线下店铺" />

		<view v-if="storeArr.length > 0" class="store-list">
			<view v-for="item in storeArr" :key="item.id" class="store-item">
				<view class="f-i-c">
					<view class="name">
						{{ item.name }}
					</view>
					<view class="distance f-i-c">
						<image class="icon" src="/src/static/images/location.png" />
						<text>距离您{{ item.distance }}</text>
					</view>
				</view>

				<view class="address">
					{{ item.position }}
				</view>
				<view class="date">
					营业时间  {{ item.open_time }}-{{ item.close_time }}
				</view>
			</view>
		</view>
		
		<wd-status-tip v-else image="content" tip="暂无门店" />
	</view>
</template>

<style lang="scss" scoped>
	.store-page {
  background-color: #fcfeff;
  .store-list {
    padding: 67px 26px 30px 26px;

    .store-item {
      font-size: 14px;
      & + .store-item {
        padding-top: 24px;
      }
      .name {
        font-weight: 600;
        line-height: 18px;
        color: #23282c;
      }

      .distance {
        padding-left: 15px;
        color: #23282c;
        .icon {
          width: 16px;
          height: 16px;
        }
      }

      .address {
        padding-top: 7px;
        color: #989898;
        font-weight: 400;
        line-height: 18px;
      }
      .date {
        padding-top: 5px;
        color: #989898;
        font-size: 12px;
        line-height: 18px;
      }
    }
  }
}
</style>
